package com.tedu.ioc;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

//模拟实现ioc控制反转，通过反射
public class BeanIoc {
    List<Bean> beans = new ArrayList<>();//多个类，存入list查询效率高
    public BeanIoc() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        Bean b1 = new Bean("user","com.tedu.ioc.User");
        Bean b2 = new Bean("dept","com.tedu.ioc.Dept");
        Bean b3 = new Bean("order","com.tedu.ioc.Order");
        Collections.addAll(beans,b1,b2,b3);
//        给bean们创造对象，控制反转Ioc   Map(key,value)
        init();
    }
        Map<String,Object> map = new ConcurrentHashMap<>();//线程安全的map
    public void init() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String key;
        Object value;
//       遍历list，获取每个bean，获取每个bean的beanId作为key存入map
//        获取每个bean的beanPath反射创建对象，作为value存入map
           for(Bean b :beans){
          key= b.getBeanId();
          value =Class.forName(b.getBeanPath()).newInstance() ;
             map.put(key,value);
       }

    }
    public  Object getBean(String leiming){
        return  map.get(leiming);
    }
}
